/*
 * Log2ExcelView.java
 */

package log2excel;

import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import log2excel.ViewInterface.RowNumberTable;
import controller.filemanager.LogParser;
//import java.io.File;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
//import java.util.Iterator;
import java.util.Iterator;
import java.util.Locale;
import javax.swing.DefaultCellEditor;
import javax.swing.GroupLayout;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import jxl.Cell;
import jxl.Sheet;
import jxl.write.Font;
import jxl.write.WritableFont;
import log2excel.ExcelManager.CreateExcel;
import log2excel.ExcelManager.OpenExcel;
import log2excel.model.ExtentionUsernameRecord;
import log2excel.ViewInterface.TableAccess;
//import log2excel.model.HLRLocationRecord;
//import log2excel.model.HLROperatorRecord;
import log2excel.model.HLRRecord;
import log2excel.model.OutgoingCallReport;
import log2excel.model.TrunkLineRecord;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

/**
 * The application's main frame.
 */
public class Log2ExcelView extends FrameView {
    private String filename = "";
    
    private void loadFileExcel(){
        JFileChooser chooser = new JFileChooser();
        FileFilter filter = new FileNameExtensionFilter("excel 2003 document", "xls");
        chooser.setFileFilter(filter);
        if (chooser.showOpenDialog(this.getComponent()) == JFileChooser.APPROVE_OPTION){
            filename = chooser.getSelectedFile().getPath();
            System.out.println(filename);
            OpenExcel oe = new OpenExcel(filename);
            
            ArrayList arrayList;
            Sheet s;
//            ExtentionUsernameRecord
            s = oe.getSheet(0);
            arrayList = new ArrayList<ExtentionUsernameRecord>();
            for(int i = 1; i < s.getRows(); i++){
                Cell[] row = s.getRow(i);
                if (row.length >= 3)
                    arrayList.add(new ExtentionUsernameRecord(row[1].getContents(), row[2].getContents()));
            }
            TableAccess.saveExtentionUsernameRecords(arrayList);
//            TrunkLineRecord
            arrayList = new ArrayList<TrunkLineRecord>();
            s = oe.getSheet(1);
            for(int i = 1; i < s.getRows(); i++){
                Cell[] row = s.getRow(i);
                if (row.length >= 3)
                    arrayList.add(new TrunkLineRecord(row[1].getContents(), row[2].getContents()));
            }
            TableAccess.saveTrunkLineRecords(arrayList);
            
//            HLRRecord
//            ArrayList<HLRLocationRecord> arrayListloc = new ArrayList<HLRLocationRecord>();
            arrayList = new ArrayList<HLRRecord>();
            s = oe.getSheet(2);
            for(int i = 1; i < s.getRows(); i++){
                Cell[] row = s.getRow(i);
                if (row.length >= 7){
                    long cost = Long.parseLong((row[4].getContents().length() == 0) ? "0" : row[4].getContents());
                    long pulse = Long.parseLong((row[5].getContents().length() == 0) ? "0" : row[5].getContents());
                    arrayList.add(new HLRRecord(row[1].getContents(), row[2].getContents(), row[3].getContents(), cost, pulse, row[6].getContents()));
                }
            }
            TableAccess.saveHLRRecords(arrayList);

            oe.close();
        }
    }
    private void saveFileExcel(boolean  saveas){
        if (filename.length() == 0)
            saveas = true;
        if (saveas){
            JFileChooser chooser = new JFileChooser();
            FileFilter filter = new FileNameExtensionFilter("excel 2003 document", "xls");
            chooser.setFileFilter(filter);
            if(chooser.showSaveDialog(this.getComponent()) == JFileChooser.APPROVE_OPTION){
                filename = chooser.getSelectedFile().getPath();
            }
        }
        if (filename.length() > 3){
            if (filename.indexOf(".") == -1){
                filename += ".xls";
            }
            CreateExcel ce = new CreateExcel(filename);
            ArrayList arraylist;
            ArrayList<String> row = new ArrayList<String>();
            
            
//            ExtentionUsernameRecords
            ce.createSheet("extention username", 0);
            arraylist = new ArrayList<ExtentionUsernameRecord>(TableAccess.getExtentionUsernameRecords());
            row.clear();
            row.add("No");
            row.add("Extention");
            row.add("User Name");
            ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
            for(int i = 0; i < arraylist.size(); i++){
                System.out.println("-"+arraylist.size());
                row.clear();
                ExtentionUsernameRecord eur = (ExtentionUsernameRecord)arraylist.get(i);
                row.add(""+i);
                row.add(eur.Extention);
                row.add(eur.Username);
                ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            }
            
//            TrunkLineRecord
            ce.createSheet("trunk line", 1);
            arraylist = new ArrayList<TrunkLineRecord>(TableAccess.getTrunkLineRecords());
            row.clear();
            row.add("No");
            row.add("Trunk");
            row.add("Line");
            ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
            for(int i = 0; i < arraylist.size(); i++){
                System.out.println("--"+arraylist.size());
                row.clear();
                TrunkLineRecord eur = (TrunkLineRecord)arraylist.get(i);
                row.add(""+i);
                row.add(eur.Trunk);
                row.add(eur.Line);
                ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            }
//            HLRRecord
            ce.createSheet("HLR", 2);
            arraylist = new ArrayList<HLRRecord>(TableAccess.getHLRRecords());
            row.clear();
            row.add("No");
            row.add("HLR");
            row.add("Operator");
            row.add("Location");
            row.add("Cost");
            row.add("Pulse(sec)");
            row.add("Type");
            ce.putRow(0, 0, row, new WritableFont(Font.ARIAL), null);
            for(int i = 0; i < arraylist.size(); i++){
                System.out.println("---"+arraylist.size());
                row.clear();
//                HLRLocationRecord eur = (HLRLocationRecord)arraylist.get(i);
                HLRRecord eur = (HLRRecord)arraylist.get(i);
                row.add(""+i);
                row.add(eur.HLR);
                row.add(eur.Operator);
                row.add(eur.Location);
                row.add("" + eur.Cost);
                row.add("" + eur.Pulse);
                row.add(eur.Type);
                ce.putRow(i+1, 0, row, new WritableFont(Font.ARIAL), null);
            }
            ce.write_close();
        }
    }
    private void chartBU(){
        DefaultPieDataset dataset = new DefaultPieDataset();
        ArrayList<HLRRecord> arrayList = TableAccess.getHLRRecords();
        while (arrayList.size() > 0){
            String type = arrayList.get(0).Type.trim();
            int count = 0;
            for (int i = 0; i < arrayList.size();){
                HLRRecord obj = arrayList.get(i);
                if (obj.Type.trim().equals(type)){
                    count++;
                    arrayList.remove(i);
                }
                else{
                    i++;
                }
            }
            dataset.setValue(type, count);
        }
        JFreeChart chart = ChartFactory.createPieChart("Type", dataset, true, true, Locale.ENGLISH);
        
        JFrame pieFrame = new ChartFrame("type Pie", chart);
        pieFrame.setSize(400, 320);
        pieFrame.setVisible(true);
    }
    public Log2ExcelView(SingleFrameApplication app) {
        super(app);

        initComponents();
        prepareTable();
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = Log2ExcelApp.getApplication().getMainFrame();
            aboutBox = new Log2ExcelAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        Log2ExcelApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTable5 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        searchField = new javax.swing.JTextField();
        searchLabel = new javax.swing.JLabel();
        refreshBtn = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 599, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 376, Short.MAX_VALUE)
        );

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(log2excel.Log2ExcelApp.class).getContext().getResourceMap(Log2ExcelView.class);
        jTabbedPane1.addTab(resourceMap.getString("jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 599, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 376, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N

        jPanel3.setName("jPanel3"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 599, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 376, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab(resourceMap.getString("jPanel3.TabConstraints.tabTitle"), jPanel3); // NOI18N

        jPanel9.setName("jPanel9"); // NOI18N

        jScrollPane5.setName("jScrollPane5"); // NOI18N

        jTableModel4 = new javax.swing.table.DefaultTableModel(
            new Object [][] {
            },
            new String [] {
                "SrN",
                "STN",
                "Username",
                "TRK",
                "Line",
                "CalledNo",
                "DATE",
                "TIME",
                "DUR",
                "UNIT",
                "AMOUNT",
                "R"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                //        return canEdit [columnIndex];
                return false;
            }
        };
        jTable5.setModel(jTableModel4);
        jTable5.setName("jTable5"); // NOI18N
        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(jTableModel4);
        jTable5.setRowSorter(sorter);
        jScrollPane5.setViewportView(jTable5);
        jTable5.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable5.columnModel.title0")); // NOI18N
        jTable5.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable5.columnModel.title1")); // NOI18N
        jTable5.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable5.columnModel.title2")); // NOI18N
        jTable5.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable5.columnModel.title3")); // NOI18N
        jTable5.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("jTable5.columnModel.title4")); // NOI18N
        jTable5.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("jTable5.columnModel.title5")); // NOI18N
        jTable5.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("jTable5.columnModel.title6")); // NOI18N
        jTable5.getColumnModel().getColumn(7).setHeaderValue(resourceMap.getString("jTable5.columnModel.title7")); // NOI18N
        jTable5.getColumnModel().getColumn(8).setHeaderValue(resourceMap.getString("jTable5.columnModel.title8")); // NOI18N
        jTable5.getColumnModel().getColumn(9).setHeaderValue(resourceMap.getString("jTable5.columnModel.title9")); // NOI18N
        jTable5.getColumnModel().getColumn(10).setHeaderValue(resourceMap.getString("jTable5.columnModel.title10")); // NOI18N
        jTable5.getColumnModel().getColumn(11).setHeaderValue(resourceMap.getString("jTable5.columnModel.title11")); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        searchField.setText(resourceMap.getString("searchField.text")); // NOI18N
        searchField.setName("searchField"); // NOI18N
        searchField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                searchFieldKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                searchFieldKeyTyped(evt);
            }
        });

        searchLabel.setText(resourceMap.getString("searchLabel.text")); // NOI18N
        searchLabel.setName("searchLabel"); // NOI18N

        refreshBtn.setText(resourceMap.getString("refreshBtn.text")); // NOI18N
        refreshBtn.setName("refreshBtn"); // NOI18N
        refreshBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addComponent(refreshBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 203, Short.MAX_VALUE)
                        .addComponent(searchLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchLabel)
                    .addComponent(refreshBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab(resourceMap.getString("jPanel9.TabConstraints.tabTitle"), jPanel9); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N
        fileMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fileMenuMouseClicked(evt);
            }
        });
        fileMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuActionPerformed(evt);
            }
        });

        jMenuItem1.setText(resourceMap.getString("openLogFileMenuitem.text")); // NOI18N
        jMenuItem1.setName("openLogFileMenuitem"); // NOI18N
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText(resourceMap.getString("openExcelFileMenuitem.text")); // NOI18N
        jMenuItem2.setName("openExcelFileMenuitem"); // NOI18N
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem2);

        jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem5.setText(resourceMap.getString("jMenuItem5.text")); // NOI18N
        jMenuItem5.setName("jMenuItem5"); // NOI18N
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem5);

        jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem6.setText(resourceMap.getString("jMenuItem6.text")); // NOI18N
        jMenuItem6.setName("jMenuItem6"); // NOI18N
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem6);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(log2excel.Log2ExcelApp.class).getContext().getActionMap(Log2ExcelView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 434, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        
        JFileChooser chooser = new JFileChooser();
        FileFilter filter = new FileNameExtensionFilter("file txt", "txt");
        chooser.addChoosableFileFilter(filter);
        if (chooser.showOpenDialog(this.getComponent()) == JFileChooser.APPROVE_OPTION){

            LogParser logparser = new LogParser( chooser.getSelectedFile().getPath());
            try {
                OutgoingCallReport.Records = logparser.createLogTable();
            } catch (ParseException ex) {
                Logger.getLogger(Log2ExcelView.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            TableAccess.saveOutgoingCallReport(OutgoingCallReport.Records);
            
            jButton1.setEnabled(true);
        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        this.loadFileExcel();
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        // TODO add your handling code here:
        saveFileExcel(false);
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_fileMenuActionPerformed

    private void fileMenuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileMenuMouseClicked
        // TODO add your handling code here:
        if (filename == null || filename.length() == 0){
            jMenuItem5.setEnabled(false);
        }
        else{
            jMenuItem5.setEnabled(true);
        }
    }//GEN-LAST:event_fileMenuMouseClicked

    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
        // TODO add your handling code here:
        saveFileExcel(true);
    }//GEN-LAST:event_jMenuItem6ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        FilterDialog filterdialog = new FilterDialog(this.getFrame(), true, FilterDialog.Option.ExtentionUsername);
        filterdialog.setVisible(true);
        if (!filterdialog.canceled){
            ReportFrame reportDialog = new ReportFrame(this.getFrame(), true, ReportFrame.Option.ExtentionUsername, filterdialog.selected, filterdialog.start, filterdialog.end, filterdialog.Duration);
            reportDialog.setVisible(true);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        FilterDialog filterdialog = new FilterDialog(this.getFrame(), true, FilterDialog.Option.TrunkLine);
        filterdialog.setVisible(true);
        if (!filterdialog.canceled){
            ReportFrame reportDialog = new ReportFrame(this.getFrame(), true, ReportFrame.Option.TrunkLine, filterdialog.selected, filterdialog.start, filterdialog.end, filterdialog.Duration);
            reportDialog.setVisible(true);
        }
    }//GEN-LAST:event_jButton3ActionPerformed
    int lastRowSearch = -1;
    private void searchFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchFieldKeyTyped

    }//GEN-LAST:event_searchFieldKeyTyped

    private void searchFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchFieldKeyPressed
        JTextField source = (JTextField) evt.getSource();
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            String text = source.getText();
//            System.out.println(text);
            if (text.length() > 0){
                lastRowSearch = search(jTableModel4, text, lastRowSearch + 1);
                if (lastRowSearch > -1){
                    jTable5.setRowSelectionInterval(lastRowSearch, lastRowSearch);
                    jTable5.scrollRectToVisible(new Rectangle(jTable5.getCellRect(lastRowSearch, 0, true)));
//                    jTable1.scrollRectToVisible(new Rectangle(jTable1.getCellRect(i, 0, true)));
                } else {
                    java.awt.Toolkit.getDefaultToolkit().beep();
                }
                System.out.println(lastRowSearch);
            }
        }
        else{
            lastRowSearch = -1;
        }
    }//GEN-LAST:event_searchFieldKeyPressed

    private void refreshBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshBtnActionPerformed
        // TODO add your handling code here:
        TableAccess.saveOutgoingCallReport(OutgoingCallReport.Records);
    }//GEN-LAST:event_refreshBtnActionPerformed
    private int search(DefaultTableModel model, String text, int start){
        for (int i = start; i < model.getRowCount(); i++){
            for (int j = 0; j < model.getColumnCount(); j++){
                if (model.getValueAt(i, j).toString().startsWith(text))
                    return i;
            }
        }
        return -1;
    }
    public static javax.swing.table.DefaultTableModel jTableModel1;
    public static javax.swing.table.DefaultTableModel jTableModel2;
    public static javax.swing.table.DefaultTableModel jTableModel3;
    public static javax.swing.table.DefaultTableModel jTableModel4;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable5;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JButton refreshBtn;
    private javax.swing.JTextField searchField;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    
    private void prepareTable(){
//        tabel extention username 
        jTableModel1 = new DefaultTableModel(
                new Object[][]{
                    {}
                },
                new String[]{
                    "Extention",
                    "Username"
                });
        JTable extusertable = new JTable(jTableModel1);
        JScrollPane spextusername = new JScrollPane(extusertable);
        JTable rowextusertable = new RowNumberTable(extusertable);
        spextusername.setRowHeaderView(rowextusertable);
        spextusername.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowextusertable.getTableHeader());
        spextusername.setSize(jPanel1.getPreferredSize());
        extusertable.addFocusListener(tableFocusListener);
        extusertable.addKeyListener(tableKeyListener);
        jPanel1.add(spextusername, BorderLayout.PAGE_START);
//        tabel trunk line
        jTableModel2 = new DefaultTableModel(
                new Object[][]{
                    {}
                },
                new String[]{
                    "Trunk",
                    "Line"
                });
        JTable trklinetable = new JTable(jTableModel2);
        JScrollPane sptrklinetable = new JScrollPane(trklinetable);
        JTable rowtrklinetable = new RowNumberTable(trklinetable);
        sptrklinetable.setRowHeaderView(rowtrklinetable);
        sptrklinetable.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowtrklinetable.getTableHeader());
        sptrklinetable.setSize(jPanel2.getPreferredSize());
        trklinetable.addFocusListener(tableFocusListener);
        trklinetable.addKeyListener(tableKeyListener);
        jPanel2.add(sptrklinetable, BorderLayout.PAGE_START);
//        tabel HLR
        jTableModel3 = new DefaultTableModel(
                new Object[][]{
                    {}
                },
                new String[]{
                    "HLR",
                    "Operator",	
                    "Location", 
                    "Cost",
                    "Pulse(sec)",
                    "Type"
                }){
                    Class[] types = new Class[]{
                        java.lang.String.class, 
                        java.lang.String.class,
                        java.lang.String.class,
                        java.lang.Long.class,
                        java.lang.Long.class,
                        java.lang.String.class
                    };
                    @Override
                    public Class getColumnClass(int columnIndex) {
                        return types [columnIndex];
                    };
                };
        String[] typeValues = new String[]{
            "Local PSTN",
            "Local GSM",
            "SLJJ PSTN",
            "SLJJ GSM",
            "SLI",
            "other"
        };
        JTable hlrtable = new JTable(jTableModel3);
        TableColumn col = hlrtable.getColumnModel().getColumn(5);
        col.setCellEditor(new DefaultCellEditor(new JComboBox(typeValues)));
        JScrollPane sphlrtable = new JScrollPane(hlrtable);
        JTable rowhlrtable = new RowNumberTable(hlrtable);
        sphlrtable.setRowHeaderView(rowhlrtable);
        sphlrtable.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowhlrtable.getTableHeader());
        sphlrtable.setSize(jPanel3.getPreferredSize());
        hlrtable.addFocusListener(tableFocusListener);
        hlrtable.addKeyListener(tableKeyListener);

//        JLabel blankSpace = new JLabel(); 
        JLabel townlabel = new JLabel("Kota : ");
        JTextField townfield = new JTextField();
        townfield.setMaximumSize(new Dimension(100, townfield.getPreferredSize().height));
        townfield.addKeyListener(townfieldKeyListener);
        GroupLayout layout = new GroupLayout(jPanel3);
        
        layout.setAutoCreateGaps(true);
        layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(townlabel)
                    .addComponent(townfield))
                .addComponent(sphlrtable));
        layout.setVerticalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(townlabel)
                    .addComponent(townfield))
                .addComponent(sphlrtable));
        jPanel3.setLayout(layout);
    }
    private KeyListener townfieldKeyListener = new KeyListener() {

        public void keyTyped(KeyEvent e) {
//            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void keyPressed(KeyEvent e) {
            JTextField source = (JTextField)e.getSource();
            if (e.getKeyCode() == KeyEvent.VK_ENTER){
                String text = source.getText().toLowerCase();
                if (text.length() > 0){
                    updateTypeHLR(text);
                }
//                System.out.println(text);
            }
        }

        public void keyReleased(KeyEvent e) {
//            throw new UnsupportedOperationException("Not supported yet.");
        }
    };
    private void updateTypeHLR(String town){
        ArrayList<HLRRecord> arrayList = TableAccess.getHLRRecords();
        int index = 0;
        for (Iterator<HLRRecord> it = arrayList.iterator(); it.hasNext();) {
            HLRRecord hLRRecord = it.next();
            boolean GSM = false;
            boolean local = false;
            boolean SLI = false;
            
            if (hLRRecord.HLR.toLowerCase().startsWith("08") || hLRRecord.HLR.toLowerCase().startsWith("+628")){
                GSM = true;
            }
            if (hLRRecord.Location.toLowerCase().contains(" "+town) || hLRRecord.Location.toLowerCase().contains(town+" ")){
                local = true;
            }
            if (SLI){
                hLRRecord.Type = "Local GSM";
            }
            else if (local){
                if (GSM){
                    hLRRecord.Type = "Local GSM";
                }else{
                    hLRRecord.Type = "Local PSTN";
                }
            }else{
                if (GSM){
                    hLRRecord.Type = "SLJJ GSM";
                }else{
                    hLRRecord.Type = "SLJJ PSTN";
                }
            }
            arrayList.set(index, hLRRecord);
            index++;
        }
        TableAccess.saveHLRRecords(arrayList);
    }
    private KeyListener tableKeyListener = new KeyListener() {

        public void keyTyped(KeyEvent e) {
            
        }

        public void keyPressed(KeyEvent e) {
            JTable source = (JTable) e.getSource();
            DefaultTableModel model = (DefaultTableModel)source.getModel();
            int lastrow = model.getRowCount() -1;
            int lastcolumn = model.getColumnCount() -1;
            int row = source.getSelectedRow();
            int column = source.getSelectedColumn();
            switch(e.getKeyCode()){
                case KeyEvent.VK_ENTER:
                    if (row == lastrow){
                        model.addRow(new Object[model.getColumnCount()]);
                    } else{
                    }
//                    column = 0;
//                    source.changeSelection(row, column, false, false);
                    break;
                case KeyEvent.VK_TAB:
                    if (column == lastcolumn){
                        if (row == lastrow){
                                model.addRow(new Object[model.getColumnCount()]);
                        } 
                        row++;
                        column = 0;
                    } else {
                        column++ ;
                    }
                    break;
            }
        }

        public void keyReleased(KeyEvent e) {
//            throw new UnsupportedOperationException("Not supported yet.");
        }
    };
    private FocusListener tableFocusListener  = new FocusListener() {

        public void focusGained(FocusEvent e) {
//            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void focusLost(FocusEvent e) {
            JTable source = (JTable)e.getSource();
            DefaultTableModel model = (DefaultTableModel)source.getModel();
            boolean empty = false;
            int lastindex = model.getRowCount() - 1;
            for (int i = 0; i < model.getColumnCount(); i++){
                if (model.getValueAt(lastindex, i) != null && model.getValueAt(lastindex, i).toString().length() > 0){
                    empty = true;
                    break;
                }
            }
            if (empty){
                model.addRow(new Object[model.getColumnCount()]);
            }
        }
    };
}
